﻿using System;
using Modbus.Messages;

namespace Modbus
{
	partial class ModbusClient
	{
		public short[] ReadFifoQueue(byte slaveAddress, int pointerAddress)
		{
			//
			// Input arguments validation.
			//

			Ensure.ArgumentNotEqualTo(SR.Argument_slaveAddress, slaveAddress, BroadcastAddress);
			Ensure.ArgumentInRange(SR.Argument_pointerAddress, pointerAddress, MinDataAddress, MaxDataAddress);

			//
			// Internal state validation.
			//

			this.ThrowIfDisposed();

			//
			// Request creation.
			//

			ReadFifoQueueRequest request = new ReadFifoQueueRequest();

			request.FunctionCode = FunctionCodes.ReadFifoQueue;
			request.PointerAddress = (ushort)(pointerAddress);

			//
			// Perform transaction.
			//

			var response = this.transport.Request<ReadDataResponse>(slaveAddress, request);

			//
			// Response validation.
			//

			if (response.Data.Length < 2)
			{
				// TODO: Throw appropriate exception.
				throw new Exception();
			}
			if ((response.Data.Length % 2) != 0)
			{
				// TODO: Throw appropriate exception.
				throw new Exception();
			}

			//
			// Prepare return value.
			//

			short[] registers = DataUtility.DecodeRegisters(response.Data);

			return registers;
		}
	}
}
